package com.esd.device.controller;

import com.esd.common.pojo.R;
import com.esd.device.entity.Device;
import com.esd.device.entity.Gateway;
import com.esd.device.entity.vo.DeviceVo;
import com.esd.device.service.DeviceService;
import com.esd.device.service.GatewayService;
import com.esd.device.utils.NumberUtils;
import com.esd.device.utils.Tcp_Utils_Nio;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("fan/operation")
public class FanOperationController extends BaseOperationController {
    @Autowired
    private Tcp_Utils_Nio tcp_utils;

    // 设置终端当前时间 新旧相同
    @PostMapping("setTime")
    public R setTime(@RequestBody DeviceVo deviceVo) {
        String commandStr = NumberUtils.longToHexString(Long.parseLong(deviceVo.getStationId()), 8);
        commandStr = commandStr + " " + "06 01";
        LocalDateTime now = LocalDateTime.now();
        int hour = now.getHour();
        int minute = now.getMinute();
        int second = now.getSecond();
        commandStr = commandStr + " " + NumberUtils.intToHexString(hour, 2)
                + " " + NumberUtils.intToHexString(minute, 2)
                + " " + NumberUtils.intToHexString(second, 2);
        R r = sendCommandForOperation(deviceVo, commandStr, tcp_utils);
        if (r.getCode() == 500) {
            return r;
        } else {
            return R.ok("同步终端" + deviceVo.getStationId() + "时间成功！！");
        }
    }

    // 设置自动启动时间 新旧相同
    @PostMapping("setStartTime/{startTime}")
    public R setStartTime(
            @RequestBody DeviceVo deviceVo,
            @PathVariable String startTime
    ) {
        String deviceIdStr = NumberUtils.longToHexString(Long.parseLong(deviceVo.getStationId()), 8);
        String[] ss = startTime.split("-");

        String commandStr1 = deviceIdStr + " " + "06 02" + " " + changeTimeStrToCommand(ss[0] + "-" + ss[1] + "-" + ss[2]);

        String commandStr2 = deviceIdStr + " " + "06 03" + " " + changeTimeStrToCommand(ss[3] + "-" + ss[4] + "-" + ss[5]);

        String commandStr3 = deviceIdStr + " " + "06 04" + " " + changeTimeStrToCommand(ss[6] + "-" + ss[7] + "-" + ss[8]);

        R r1 = sendCommandForOperation(deviceVo, commandStr1, tcp_utils);
        R r2 = sendCommandForOperation(deviceVo, commandStr2, tcp_utils);
        R r3 = sendCommandForOperation(deviceVo, commandStr3, tcp_utils);

        String resultStr1 = r1.getMsg();
        String resultStr2 = r2.getMsg();
        String resultStr3 = r3.getMsg();
        if (r1.getCode() == 500 || r2.getCode() == 500 || r3.getCode() == 500) {
            if (resultStr1.equals("error") || resultStr2.equals("error") || resultStr3.equals("error")) {
                return R.error("请检查网关是否正常工作！！");
            } else if (resultStr1.equals("") || resultStr2.equals("") || resultStr3.equals("")) {
                return R.error("无返回数据，终端是否正常运行？");
            }
            return R.error("终端" + deviceVo.getStationId() + "自启动时间设置失败，请检查终端");
        } else {
            return R.ok("终端" + deviceVo.getStationId() + "自启动时间设置成功！！");
        }
    }

    // 设置休眠时间 新旧相同
    @PostMapping("setSleepTime/{sleepTime}")
    public R setSleepTime(
            @RequestBody DeviceVo deviceVo,
            @PathVariable String sleepTime
    ) {
        String deviceIdStr = NumberUtils.longToHexString(Long.parseLong(deviceVo.getStationId()), 8);

        String[] ss = sleepTime.split("-");

        String commandStr1 = deviceIdStr + " " + "06 05" + " " + changeTimeStrToCommand(ss[0] + "-" + ss[1] + "-" + ss[2]);

        String commandStr2 = deviceIdStr + " " + "06 06" + " " + changeTimeStrToCommand(ss[3] + "-" + ss[4] + "-" + ss[5]);

        String commandStr3 = deviceIdStr + " " + "06 07" + " " + changeTimeStrToCommand(ss[6] + "-" + ss[7] + "-" + ss[8]);

        R r1 = sendCommandForOperation(deviceVo, commandStr1, tcp_utils);
        R r2 = sendCommandForOperation(deviceVo, commandStr2, tcp_utils);
        R r3 = sendCommandForOperation(deviceVo, commandStr3, tcp_utils);

        String resultStr1 = r1.getMsg();
        String resultStr2 = r2.getMsg();
        String resultStr3 = r3.getMsg();
        if (r1.getCode() == 500 || r2.getCode() == 500 || r3.getCode() == 500) {
            if (resultStr1.equals("error") || resultStr2.equals("error") || resultStr3.equals("error")) {
                return R.error("请检查网关是否正常工作！！");
            } else if (resultStr1.equals("") || resultStr2.equals("") || resultStr3.equals("")) {
                return R.error("无返回数据，终端是否正常运行？");
            }
            return R.error("终端" + deviceVo.getStationId() + "休眠时间设置失败，请检查终端");
        } else {
            return R.ok("终端" + deviceVo.getStationId() + "休眠时间设置成功！！");
        }
    }

    // 修改自动清扫时间 新旧相同
    @PostMapping("setCleanTime/{cleanTime}")
    public R setCleanTime(@RequestBody DeviceVo deviceVo, @PathVariable String cleanTime) {
        String commandStr = NumberUtils.longToHexString(Long.parseLong(deviceVo.getStationId()), 8)
                + " " + "06 08" + " " + changeTimeStrToCommand(cleanTime);
        R r = sendCommandForOperation(deviceVo, commandStr, tcp_utils);
        if (r.getCode() == 500) {
            return r;
        } else {
            return R.ok("终端" + deviceVo.getStationId() + "自动清扫时间设置成功！！");
        }
    }

    // 修改平衡电压上下限 新旧相同
    @PostMapping("setBalancePower/{scale}")
    public R setBalancePowerLimit(
            @RequestBody DeviceVo deviceVo, @PathVariable String scale
    ) {
        String commandStr = NumberUtils.longToHexString(Long.parseLong(deviceVo.getStationId()), 8)
                + " " + "06 0A 00" + " " + changeScaleToStr(scale);
        R r = sendCommandForOperation(deviceVo, commandStr, tcp_utils);
        if (r.getCode() == 500) {
            return r;
        } else {
            return R.ok("终端" + deviceVo.getStationId() + "平衡电压上下限成功设置为: " + scale + " 伏特！！");
        }
    }

    // 修改最长保养时间 新旧相同
    @PostMapping("setMaintainTime/{maintainTime}")
    public R setMaintainTime(
            @RequestBody DeviceVo deviceVo,
            @PathVariable Integer maintainTime
    ) {
        String commandStr = NumberUtils.longToHexString(Long.parseLong(deviceVo.getStationId()), 8)
                + " " + "06 0D 00" + " " + NumberUtils.intToHexString(maintainTime, 4);
        R r = sendCommandForOperation(deviceVo, commandStr, tcp_utils);
        if (r.getCode() == 500) {
            return r;
        } else {
            return R.ok("终端" + deviceVo.getStationId() + "最长保养时间成功设置为: " + maintainTime + " 小时！！");
        }
    }

    // 修改放电针上下限 新旧相同
    @PostMapping("setPowerLimit/{scale}")
    public R setPowerLimit(
            @RequestBody DeviceVo deviceVo, @PathVariable String scale
    ) {
        String commandStr = NumberUtils.longToHexString(Long.parseLong(deviceVo.getStationId()), 8)
                + " " + "06 0F 00" + " " + changeScaleToStr(scale);
        R r = sendCommandForOperation(deviceVo, commandStr, tcp_utils);
        if (r.getCode() == 500) {
            return r;
        } else {
            return R.ok("终端" + deviceVo.getStationId() + "放电针电压上下限成功设置为: " + scale + " 伏特！！");
        }
    }

    // 修改风扇档位 新旧相同
    @PostMapping("setFanLevel/{fanLevel}")
    public R setFanLevel(
            @RequestBody DeviceVo deviceVo,
            @PathVariable Integer fanLevel
    ) {
        String commandStr = NumberUtils.longToHexString(Long.parseLong(deviceVo.getStationId()), 8)
                + " " + "06 11 00 00" + NumberUtils.intToHexString(fanLevel, 2);
        R r = sendCommandForOperation(deviceVo, commandStr, tcp_utils);
        if (r.getCode() == 500) {
            return r;
        } else {
            return R.ok("终端" + deviceVo.getStationId() + "调整到" + fanLevel + "档风速成功");
        }
    }

    // 修改开关机， 新旧相同
    @PostMapping("setPowerSwitch/{powerSwitch}")
    public R setPowerSwitch(
            @RequestBody DeviceVo deviceVo,
            @PathVariable String powerSwitch
    ) {
        String commandStr = NumberUtils.longToHexString(Long.parseLong(deviceVo.getStationId()), 8)
                + " " + "06 12 00 00" + " " + powerSwitch;
        Map<String, String> map = new HashMap<>();
        map.put("01", "开机");
        map.put("00", "关机");
        R r = sendCommandForOperation(deviceVo, commandStr, tcp_utils);
        if (r.getCode() == 500) {
            return r;
        } else {
            return R.ok("终端" + deviceVo.getStationId() + map.get(powerSwitch) + "成功！！");
        }
    }

    @PostMapping("/fanLevelLock/{fanLevelStatus}")
    public R fanLevelLock(
            @RequestBody DeviceVo deviceVo,
            @PathVariable String fanLevelStatus
    ) {
        String commandStr = NumberUtils.longToHexString(Long.parseLong(deviceVo.getStationId()), 8)
                + " " + "06 09 00 00" + " " + fanLevelStatus;
        Map<String, String> map = new HashMap<>();
        map.put("00", "风挡解锁");
        map.put("01", "风挡锁定");
        R r = sendCommandForOperation(deviceVo, commandStr, tcp_utils);
        if (r.getCode() == 500) {
            return r;
        } else {
            return R.ok("终端" + deviceVo.getStationId() + map.get(fanLevelStatus) + "成功！！");
        }
    }

    @Autowired
    private GatewayService gatewayService;

    @Autowired
    private DeviceService deviceService;

    @PostMapping("setSignalChannel/{change_gatewayId}")
    public R setSignalChannel(
            @PathVariable Integer change_gatewayId,
            @RequestBody DeviceVo deviceVo
    ) {
        Gateway gateway1 = gatewayService.getById(change_gatewayId);
        if (gateway1.getGatewayId().intValue() == deviceVo.getGatewayId().intValue()) {
            return R.error("修改前和修改后网关及信道都相同，无需修改！！");
        }
        Device device = deviceService.getById(deviceVo.getDeviceId());
        String hexString = NumberUtils.longToHexString(Long.parseLong(deviceVo.getStationId()), 8);
        String sc = NumberUtils.intToHexString(gateway1.getSignalChannel(), 2);
        String commandStr = hexString + " " + "06 13 00 00" + " " + sc;
        R r = sendCommandForOperation(deviceVo, commandStr, tcp_utils);
        if (r.getCode() == 500) {
            return r;
        } else {
            device.setGatewayId(gateway1.getGatewayId());
            device.setSignalChannel(gateway1.getSignalChannel());
            deviceService.updateById(device);
            return R.ok("终端" + deviceVo.getStationId() + "信道成功修改为" + gateway1.getSignalChannel() + "！！");
        }
    }
}
